<?php
include ("connection.php");
$CarpetaDestino = '../img/';

if (!@file_exists($CarpetaDestino)) {
	//si la carpeta de destino no existe
	die("La carpeta para almacenar las imagenes no existe");
}

if ($_FILES["file"]["error"] > 0)
  {
  echo "Error: " . $_FILES["file"]["error"] . "<br>";
  }
else
  {
  	$FileName = strtolower($_FILES['file']['name']); 
  	$ImageExt = substr($FileName, strrpos($FileName, '.')); 
	$FileType = $_FILES['file']['type']; 
	$FileSize = $_FILES['file']["size"]; 
	$uploaded_date	= date("Y-m-d H:i:s");
  }


  if($_POST)
{	
	$shortDescription = $_POST['shortDescription'];
	$ImageExt = substr($FileName, strrpos($FileName, '.')); 
	$FileType = $_FILES['file']['type']; 
	$FileSize = $_FILES['file']["size"]; 
	$uploaded_date	= date("Y-m-d H:i:s");
	
	switch(strtolower($FileType))
	{
	
		case 'image/png': //png file
		case 'image/gif': //gif file 
		case 'image/jpeg': //jpeg file
			break;
		default:
			die('Archivo Incompatible'); 
	}

  
	$FileName = preg_replace(array('/\s/', '/\.[\.]+/', '/[^\w_\.\-]/'), array('_', '.', ''), strtolower($FileName));
	$FileName = $FileName.'_'.$ImageExt;
   
   if(move_uploaded_file($_FILES['file']["tmp_name"], $CarpetaDestino . $FileName ))
   {
		//base de datos

		$link = ConnectDB();
		$stmt = $link->prepare("INSERT INTO  projects (ShortDescription,FullDescription,Images,MainImage) VALUES (?,?,?,?);");
		$stmt->bind_param('ssss', $shortDescription, $shortDescription , $shortDescription , $FileName);
		$stmt->execute();
		$stmt->close();

		echo ('/Garmor/web/img/'.$FileName);
		//die ('/Applications/XAMPP/xamppfiles/htdocs/Garmor/web/img/'.$FileName);
		
   }else{

   		echo('no');
   		die('error uploading File!');
   }
}

	function ConnectDB(){
		/*
		$mysqli = new mysqli("localhost", "root", "", "Garmor", 3306);
		if ($mysqli->connect_errno) {
		    echo "Fallo al conectar a MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
		}
		*/
		
		$mysqli = new connection();
		if ($mysqli->connect_errno) {
		    echo "Fallo al conectar a MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
		}
		
		return $mysqli;
	}

?>